$(function(){
	
	var $btnSave = $('#btnAdd');
	$btnSave.click(function(){
		adminAdd();
	});
	

	//全选
	var $check_all = $("#check_all");
	var $check_roles = $("input[name='roles']");
	
	$check_all.click(function(){
		
		var checked = false;
		if($(this).is(':checked')){
			checked = true;
		}
		
		$check_roles.each(function(i){
			var $check = $($check_roles[i]);
			
			if(checked){
				if(!$check.is(':checked')){
					$check.click();
				}
			}else{
				if($check.is(':checked')){
					$check.click();
				}
			}
		});
		
	});


    //角色权限选择
    $('#group_id').change(function(){

        //先取消全部
        $check_roles.each(function(i){
            var $check = $($check_roles[i]);

                if($check.is(':checked')){
                    $check.click();
                }

        });


        var group_roles = $(this).find('option:selected').attr('group_roles');
        var roles = group_roles.split(",");

        //如果有权限，选中
        $check_roles.each(function(i){
            var $check = $($check_roles[i]);

            for(var i=0;i<roles.length;i++){
                if(roles[i] == $check.val()){
                    $check.click();
                }
            }
        });

    });

});

function adminAdd(){
	
	var $name 			= $('#name');
	var $real_name 		= $('#real_name');
	var $email	 		= $('#email');
	var $passwd 		= $('#passwd');
	var $repasswd 		= $('#repasswd');
	var $mobile_phone 	= $('#mobile_phone');
	var $remark 		= $('#remark');
	var $roles			= $("input[name='roles']:checked");
	var $group_id 		= $('#group_id');
	
	
	var name 			= $name.val();
	var real_name 		= $real_name.val();
	var email 			= $email.val();
	var passwd 			= $.trim($passwd.val());
	var repasswd 		= $.trim($repasswd.val());
	var mobile_phone 	= $mobile_phone.val();
	var remark			= $remark.val();
	var disabled 		= $('input[name="disabled"]:checked').val();
	var group_id		= $group_id.val();
	
	
	if(passwd != repasswd){
		alert('两次密码输入不一致');
		return false;
	}else if(passwd == ''){
		alert('请填写密码');
		return false;
	}
	
	
	var roles = new Array();
	
	$roles.each(function(i){
		roles.push($(this).val());
	});
	

	var params = {
		'name'			:name,
		'passwd'		:passwd,
		'repasswd'		:repasswd,
		'real_name'		:real_name,
		'email'			:email,
		'mobile_phone'	:mobile_phone,
		'remark'		:remark,
		'group_id'		:group_id,
		'role'			:roles.toString(),		
		'disabled'		:disabled
	}

	$.post('/index.php/Admin/Admin/add_do',params,function(data){
		if(data.success){
			alert('管理员添加成功');
			location.href = '/index.php/Admin/Admin/';
		}else{
			alert('管理员添加失败');
		}
	},'json');
}
